package pro.wyn.servlet;


import pro.wyn.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/wyn2Login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("u");
        String password = request.getParameter("p");

        System.out.println("usernsme="+username);
        System.out.println("password="+password);

        String code = request.getParameter("c");
        HttpSession session = request.getSession();
        Object ccc = session.getAttribute("ccc");

        boolean isTrue = code !=null && code.equals(ccc);
        if(!isTrue){
            PrintWriter writer = response.getWriter();
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }

        String sql="SELECT id FROM `user` where username=? and `password`=?";
        Integer id = JdbcUtils.select(sql,Integer.class,username,password);
        if(id !=null&&id>0){
            //
            session.setAttribute("UID",id);
            //重定向到首页
            response.sendRedirect("/wyn/index.jsp");
        } else {
            //重定向到登录页
            response.sendRedirect("/wyn/login.jsp");
        }

    }
}
